<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>宠物管理</el-breadcrumb-item>
      <el-breadcrumb-item>宠物热点管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-form
      :model="hotForm"
      :rules="hotFormRules"
      ref="hotFormRef"
      label-width="100px"
      label-position="left"
    >
      <el-card>
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-form-item label="标题" prop="title">
          <el-input
            type="textarea"
            v-model="hotForm.title"
            show-word-limit
            maxlength="30"
            placeholder="请输入热点的标题，建议30字以内"
          ></el-input>
        </el-form-item>
        <el-form-item label="热点分类" prop="classify">
          <el-select
            v-model="hotForm.classify"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.get_hot_class"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物类别" prop="pets_kinds">
            <el-radio-group v-model="hotForm.pets_kinds">
              <el-radio label="2">猫</el-radio>
              <el-radio label="1">狗</el-radio>
              <el-radio label="3">猫狗通用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="热点类型" prop="hot_class">
            <el-select
              v-model="hotForm.hot_class"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option label="文章" value="1"></el-option>
              <el-option label="视频" value="2"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="banner图" prop="banner">
          <el-upload
            :action="ossUrl"
            :headers="ossHeader"
            list-type="picture-card"
            :auto-upload="true"
            :limit="imgLimit"
            :on-exceed="handleExceed"
            v-model="hotForm.banner"
            :on-success="uploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :data="{ system: 'chongtai', module: '商品图片' }"
            :class="{ uoloadSty: showBtnImg, disUoloadSty: noneBtnImg }"
            :on-change="imgChange"
            :before-upload="beforeUpload"
            :file-list="bannerList"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div
              style="transform: translateY(-85%); color: grey; font-size: 14px"
            >
              上传图片
            </div>
            <div class="el-upload__tip" slot="tip">
              <ul style="margin-left: -25px; line-height: 20px; color: grey">
                <li>请上传jpg或png格式的图片，大小不超过2M。最多上传3张</li>
                <li>上传的图片尺寸为690*540px，或与之等比例的图片</li>
              </ul>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="推文链接" prop="is_push">
          <el-radio-group v-model="hotForm.is_push">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="是否推文"
          prop="push_link"
          v-show="hotForm.is_push == 1"
          :rules="
            hotForm.is_push == 1
              ? [{ required: true, message: '请输入', trigger: 'blur' }]
              : []
          "
        >
          <el-input v-model="hotForm.push_url" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="hotForm.remark"
            show-word-limit
            maxlength="500"
            placeholder="请输入备注说明"
          ></el-input>
        </el-form-item>
      </el-card>

      <el-card v-show="hotForm.is_push == 0" class="cardTop">
        <div slot="header">
          <span>热点内容</span>
        </div>
        <el-form-item
          prop="content"
          :rules="
            hotForm.is_push == 0
              ? [{ required: true, message: '请输入', trigger: 'blur' }]
              : []
          "
        >
          <el-row v-loading="quillUpdateImg" class="nolabel">
            <quill-editor
              v-model="hotForm.content"
              ref="myQuillEditorQ"
              :options="editorOption"
              @change="onEditorChange($event)"
              class="editor space-ql-editor"
            ></quill-editor>

            <!-- 图片上传组件辅助-->
            <el-upload
              class="quill-uploader"
              :action="ossUrl"
              :headers="ossHeader"
              :show-file-list="false"
              :on-success="uploadSuccessQ"
              :on-error="uploadErrorQ"
              :before-upload="beforeUploadQ"
            >
            </el-upload>
          </el-row>
        </el-form-item>
      </el-card>
    </el-form>
    <el-row style="margin-top: 10px">
      <el-button @click="$router.push('/pets/HotSpotsManage')">
        取 消
      </el-button>
      <el-button class="theme-background-color" @click="saveInfo"
        >保 存</el-button
      >
    </el-row>

    <!-- 放大图片弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="45%">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import toolbarOptions from '../../assets/js/quillToolbar.js'
export default {
  data() {
    return {
      selectData: {

      },
      hotForm: {
        title: '',
        type: '',
        banner: [],
        is_push: '0',
        push_url: '',
        remark: '',
        content: ''
      },
      hotFormRules: {
        title: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        classify: [{ required: true, message: '请选择', trigger: 'change' }],
        hot_class: [{ required: true, message: '请选择', trigger: 'change' }],
        pets_kinds: [{ required: true, message: '请选择', trigger: 'change' }],
        banner: [{ required: true, message: '请上传' }],
        is_push: [{ required: true, message: '请选择', trigger: 'change' }]
      },

      //   图片信息
      dialogImageUrl: '',
      dialogVisible: false,
      ossUrl: this.GLOBAL.ossUrl,
      ossHeader: this.GLOBAL.ossHeader,
      imgLimit: 3,
      showBtnImg: true,
      noneBtnImg: false,
      bannerList: [],

      // 富文本编辑器配置
      editorOption: {
        // 主题
        theme: 'snow',
        placeholder: '请输入正文',
        //  富文本编辑器配置
        modules: {
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.quill-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画
      imgUrl: ''
    }
  },
  created() {
    this.getSelectData()
    this.getHotInfo()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/Data/find', {
        code: 'get_hot_class'
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    async getHotInfo() {
      const { data: res } = await this.$http.post(
        '/admin/PetsHot/hotInfo',
        {
          id: this.$route.query.id
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 返回结果
      var innerArr = []
      for (var i = 0; i < res.data.banner.length; i++) {
        innerArr.push({ name: 'aaa' + i + '.jpeg', url: res.data.banner[i] })
      }
      this.bannerList = innerArr
      res.data.pets_kinds = res.data.pets_kinds + ""
      res.data.classify = parseInt(res.data.classify)
      res.data.hot_class = res.data.hot_class + ""
      if (res.data.push_url == '') {
        res.data.is_push = '0'
      } else {
        res.data.is_push = '1'
        res.data.push_link = res.data.push_url
      }

      this.hotForm = res.data
      this.hospital_id = Number.parseInt(this.$route.query.id)
    },
    async saveInfo() {
      this.$refs.hotFormRef.validate(async (valid) => {
        if (!valid) return
        this.hotForm.hot_id = this.$route.query.id
        const { data: res } = await this.$http.post('/admin/PetsHot/addHot', this.hotForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/pets/HotSpotsManage')
      })
    },

    // 超出限制时的行为
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ` +
          this.imgLimit +
          ` 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
      )
    },
    uploadSuccess(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        this.hotForm.banner.push(response.data.url)
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
    },
    // 放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //   删除图片
    handleRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      var a = this.hotForm.banner.findIndex(
        (item) => item === file.url
      )
      if (a !== -1) {
        this.hotForm.banner.splice(a, 1)
      }
      this.noneBtnImg = fileList.length >= this.imgLimit
    },
    imgChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.imgLimit
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      this.hotForm.content = html
    },
    // 上传图片成功
    uploadSuccessQ(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      console.log(this.$refs)
      const quill = this.$refs.myQuillEditorQ.quill
      // 如果上传成功
      if (Number.parseInt(res.code) === 10001) {
        console.log(res.data.url)
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadErrorQ(res, file) {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    // 上传图片前
    beforeUploadQ(file) {
      // 显示loading动画
      this.quillUpdateImg = true
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  .el-select {
    width: 100%;
  }
}
/deep/.el-upload--picture-card {
  width: 138px;
  height: 108px;
  line-height: 106px;
}
/deep/ .uoloadSty .el-upload--picture-card {
  display: true;
}
/deep/ .disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
/deep/ .uoloadSty .el-upload-list__item {
  width: 138px;
  height: 108px;
}

/deep/.editor {
  line-height: normal !important;
  height: 700px;
}
/deep/.ql-container {
  height: 640px;
}

.nolabel {
  margin-top: -20px;
  margin-left: -100px;
}
.cardTop {
  margin-top: 10px;
  /deep/.el-form-item__error {
    margin-left: -100px;
  }
}
</style>
